<?php
class HomeController extends Controller{

    public $layout='//layouts/home';
    //left-category
    public function LeftCategory(){
        $modelCategory = new Category();
        $listleftcategory = $modelCategory->findAll("parent_id=3");
        return $listleftcategory;
    }

    public function ItemNote(){
        $model = new Note();
        $notemodel = $model->FindByPk('1');
        return $notemodel;
    }

    public function ListNote(){
        $model = new Note();
        $notemodel = $model->findAll();
        return $notemodel;
    }

    //Bannerleft
    public function BannerLeft(){
        $modelBanner = new Banner();
        return  $modelBanner->findAll('type_id =1');
    }
    //BannerRight
    public function BannerRight(){
        $modelBanner = new Banner();
        return  $modelBanner->findAll('type_id =2');
    }
    // đêm số lượt đang truy cập
    public function useronline(){
        $ip = $_SERVER['REMOTE_ADDR'];
        $url =  $_SERVER['PHP_SELF'];
        $tg = time();
        $tgout = 120;
        $tgnew = $tg-$tgout;
        $modelUserOnline = new UserOnline();
        $modelUserOnline ->tgtmp = $tg;
        $modelUserOnline ->ip = $ip;
        $modelUserOnline ->local = $url;
        $modelUserOnline->save();
        $del = $modelUserOnline->deleteAll("tgtmp<$tgnew");
        $online2 = $modelUserOnline ->findAll(array(
            'select'=>'ip',
            'distinct'=>true,
        ));
        return $dem = count($online2);
    }

    //tổng số lượt truy cập
    public function sumvisit(){
        session_start();
        if(isset($_SESSION['visit']['ip'])){
            $modelvisitwebsite = new VisitWebsite();
            $sumvisit = $modelvisitwebsite->findByPk(0);
            $counter = $sumvisit['Counter'];
            $sumvisit->Counter= $counter;
            $sumvisit->update();
            return $counter;
        }else{
            $modelvisitwebsite = new VisitWebsite();
            $sumvisit = $modelvisitwebsite->findByPk(0);
            $counter = $sumvisit['Counter'];
            $sumvisit->Counter= $counter+1;
            $_SESSION['visit']['ip'] = $_SERVER['REMOTE_ADDR'];
            $sumvisit->update();
            return $counter;
        }

    }

    //thong tin sản phẩm
    public function InfoProduct($id){
        $modelproduct = new Product();
        $item = $modelproduct->FindByPk($id);
        return $item;
    }
    //danh sach tin
    public function ListNew(){
        $model = new Note();
        $listnote = $model->findAll(array('limit'=>3));
        return $listnote;
    }

    //ảnh slide sản phẩm
    public function SlideProduct($id){
        $modelimages = new Images();
        $images = $modelimages->findAll("product_id =$id");
        return $images;
    }

    //SẢN PHẨM CÙNG DANH MỤC
    public function SameProduct($category_id){
        $modelsameproduct = new Product();
        $sameproduct = $modelsameproduct->findAll("category_id = $category_id");
        return $sameproduct;
    }
    //SẢN PHẨM CÙNG XUẤT SỨ
    Public function SameType($type_id){
        $model = new Product();
        $sametype = $model->findAll($type_id);
        return $sametype;
    }

	public function actionIndex(){
        //thống kê user đang truy cập
        $dem = $this->useronline();
        //thống kê tổng số lượt truy cập
        $sumvisit =  $this->sumvisit();
        //thống kê sản phẩm
        $modelProduct = new Product();
        $listproduct = $modelProduct->findAll();
        //danh sach tin
        $listnew = $this->ListNew();
        //left-category
        $listleftcategory = $this->LeftCategory();
        //banner-left
        $bannerleft = $this->BannerLeft();
        //banner-right
        $bannerright = $this->Bannerright();
        //san-pham-ban-chay
        $sellingproducts = $modelProduct->findAll(array('order'=>'buy asc','limit' => '5','offset' => '1'));
        //phan-trang
        isset($_GET['pageid'])? $pageid = $_GET['pageid'] : $pageid = 0;
        $sumproduct = count($listproduct);
        $numberproduct = 6;
        $sumpage = ceil($sumproduct/$numberproduct);
        $offset = $pageid * $numberproduct;
        $listproduct = $modelProduct->findAll(array('limit' => "$numberproduct",'offset' => "$offset"));
        // đưa ra view
        $this->render('index',array('listproduct'=>$listproduct,'listnew'=>$listnew,'listleftcategory'=>$listleftcategory, 'bannerleft'=>$bannerleft, 'bannerright'=>$bannerright, 'sellingproducts'=>$sellingproducts,'sumpage'=>$sumpage, 'dem'=>$dem, 'sumvisit'=>$sumvisit));
    }


    public function actionDetailProduct(){
        if(isset($_GET['id']) && is_numeric($_GET['id'])){
            $id = $_GET['id'];
            //thông tin sản phẩm
            $item = $this->InfoProduct($id);
            //ảnh slide sản phẩm
            $images = $this->SlideProduct($id);
            //left-category
            $listleftcategory = $this->LeftCategory();
            //sản phẩm cùng loại
            $sameproduct = $this->SameProduct("$item->category_id");
            //sản phẩm cùng xuất sứ
            $sametype = $this->SameType($item->type_id);

            $this->render('detailproduct',array('listleftcategory'=>$listleftcategory,'item'=>$item, 'images'=>$images, 'sameproduct'=>$sameproduct, 'sametype'=>$sametype));
        }else{
            $this->redirect('index.php?r=home/index');
        }
    }



    public function actionListSameProduct(){

        if(is_numeric($_GET['id'])){
            $id = $_GET['id'];
            $dem = $this->useronline();
            $sumvisit =  $this->sumvisit();
            $modelProduct = new Product();
            $listproduct = $modelProduct->findAll("category_id = $id");

            //left-category
            $listleftcategory = $this->LeftCategory();
            //banner-left
            $bannerleft = $this->BannerLeft();
            //banner-right
            $bannerright = $this->Bannerright();
            //san-pham-ban-chay
            $sellingproducts = $modelProduct->findAll(array('order'=>'buy asc','limit' => '5','offset' => '1'));
            //phan-trang
            isset($_GET['pageid'])? $pageid = $_GET['pageid'] : $pageid = 0;
            $sumproduct = count($listproduct);
            $numberproduct = 6;
            $sumpage = ceil($sumproduct/$numberproduct);
            $offset = $pageid * $numberproduct;
            $listproduct = $modelProduct->findAll("category_id = $id",array('limit' => "$numberproduct",'offset' => "$offset"));
            $listnew = $this->ListNew();
            // đưa ra view
            $this->render('index',array('listproduct'=>$listproduct,'listleftcategory'=>$listleftcategory, 'bannerleft'=>$bannerleft, 'bannerright'=>$bannerright, 'sellingproducts'=>$sellingproducts,'sumpage'=>$sumpage, 'dem'=>$dem, 'sumvisit'=>$sumvisit,'listnew'=>$listnew));
        }else{
            $this->redirect('index.php?r=home/index');
        }

    }

    public function actionRouter(){
        switch ($_GET['id']) {
            case '1':
                $this->redirect('index.php?r=home/index');
                break;
            case '2':
                $this->redirect('index.php?r=home/gioithieu');
                break;
            case '3':
                $this->redirect('index.php?r=home/sanpham');
                break;
            case '4':
                $this->redirect('index.php?r=home/huongdanmuahang');
                break;
            case '5':
                $this->redirect('index.php?r=home/tintuc');
                break;
            case '6':
                $this->redirect('index.php?r=home/Lienhe');
                break;
            default: $this->redirect('index.php?r=home/index');
        }
    }
    public function actionSanPham(){
        $model = new Product();
        $listproduct = $model->findAll();
        //banner-left
        $bannerleft = $this->BannerLeft();
        //banner-right
        $bannerright = $this->Bannerright();
        //left-category
        $listleftcategory = $this->LeftCategory();
        $listnew = $this->ListNew();
        $this->render('sanpham',array('listproduct'=>$listproduct,'bannerleft'=>$bannerleft, 'bannerright'=>$bannerright,'listnew'=>$listnew,'listleftcategory'=>$listleftcategory ));
    }
    public function actionTinTuc(){
        //left-category
        $listleftcategory = $this->LeftCategory();
        $itemfirst = $this->ItemNote();
        $model = new Note;
        $listnew = $this->ListNew();
        $listnote = $model->findAll('category_id=5');
        $this->render('tintuc',array('listleftcategory'=>$listleftcategory,'itemfirst'=>$itemfirst,'listnote'=>$listnote,'listnew'=>$listnew));
    }
    public function actionXemThem(){
        if(is_numeric($_GET['id'])){
            $id = $_GET['id'];
            $listleftcategory = $this->LeftCategory();
            $model = new Note();
            $content = $model->findByPk($id);
            $this->render('xemthem',array('listleftcategory'=>$listleftcategory,'content'=>$content));
        }else{
            echo 'không hợp lệ';
        }
    }
    public function actionHuongDanMuahang(){
        $listleftcategory = $this->LeftCategory();
        $model = new Note;
        $listnew = $this->ListNew();
        $content = $model->findAll('category_id=4');
        $this->render('huongdanmuahang',array('listleftcategory'=>$listleftcategory,'content'=>$content,'listnew'=>$listnew));
    }
    public function actionGioiThieu(){
        $listleftcategory = $this->LeftCategory();
        $model = new Note;
        //danh sach tin
        $listnew = $this->ListNew();
        $content = $model->findAll('category_id=2');
        $this->render('gioithieu',array('listleftcategory'=>$listleftcategory,'content'=>$content,'listnew'=>$listnew));
    }
    public function actionLienhe(){
        $this->render('lienhe');
    }

    public function actionBuyProduct(){
        session_start();
        if(isset($_GET['id'])){
            if(is_numeric($_GET['id'])){
                $id = $_GET['id'];
            }else{
                $id = null;
                die;
            }
            $product = Product::model()->findByPk($id);
            $_SESSION['cart'][$id]['id']= $product->id;
            $_SESSION['cart'][$id]['name']= $product->name;
            $_SESSION['cart'][$id]['cost']= $product->cost;
            $_SESSION['cart'][$id]['images']= $product->images;
            $_SESSION['cart'][$id]['category_id']= $product->category_id;
            if(!isset($_SESSION['cart'][$id]['qty'])){
                $_SESSION['cart'][$id]['qty'] = 1;
            }else{
                if($_SESSION['cart'][$id]['id'] == $id){
                    $_SESSION['cart'][$id]['qty'] = $_SESSION['cart'][$id]['qty'] +1;
                }else{
                    $_SESSION['cart'][$id]['qty'] =1;
                }
            }
            $_SESSION['cart'][$id]['sumcost'] = $_SESSION['cart'][$id]['qty'] * $_SESSION['cart'][$id]['cost'];
            $count=0;
            foreach($_SESSION['cart'] as $key => $value){
                $count = $count + $value['sumcost'];
            }
            $_SESSION['cart']['count']= $count;
            $cart = $_SESSION['cart'];

        }else{
            $cart=$_SESSION['cart'];
            foreach($_POST as $key=>$value){
                if(is_array($value)){
                    $_SESSION['cart'][$key]['qty']= $value['qty'];
                }
            }
            $count=0;
            foreach($_SESSION['cart'] as $key => $value){
                if(is_array($value)){
                    $_SESSION['cart'][$key]['sumcost'] = $_SESSION['cart'][$key]['qty'] * $_SESSION['cart'][$key]['cost'];
                }
            }
            $count=0;
            foreach($_SESSION['cart'] as $key => $value){
                $count = $count + $value['sumcost'];
            }
            $_SESSION['cart']['count']= $count;
            $cart = $_SESSION['cart'];
        }
        $this->render('buyproduct',array('cart'=>$cart));
    }

    public function actionPay(){
        session_start();
        if(isset($_SESSION['cart'])){
            $cart = $_SESSION['cart'];
            $this->render('pay',array('cart'=>$cart));
        }else{
            $this->redirect('index.php?r=home/index');
        }

    }

    public function actionPayEnd(){
        session_start();
        isset($_POST['custom_name'])? $custom_name=$_POST['custom_name']:$custom_name="";
        isset($_POST['custom_request'])? $custom_request=$_POST['custom_request']:$custom_request="";
        isset($_POST['custom_email'])? $custom_email=$_POST['custom_email']:$custom_email="";
        isset($_POST['custom_tel'])? $custom_tel=$_POST['custom_tel']:$custom_tel="";
        isset($_POST['custom_address'])? $custom_address=$_POST['custom_address']:$custom_address="";
        isset($_POST['custom_pay'])? $custom_pay=$_POST['custom_pay']:$custom_pay="";
        isset($_SESSION['cart']['count'])? $custom_thanhtien = $_SESSION['cart']['count']:$custom_thanhtien="";
        $tockenkey=rand(0,999). substr(time(),4,9).md5($custom_name).rand(0,9999);
        $model= new order();

        $model->fullname=$custom_name;
        $model->email=$custom_email;
        $model->telephone=$custom_tel;
        $model->address = $custom_address;
        $model->pay = $custom_pay;
        $model->order_different = $custom_request;
        $model->money = $custom_thanhtien;
        $model->tockenkey = $tockenkey;
        $check1=$model->save();



        $custom = $model->findAll('tockenkey="'.$tockenkey.'"');
        foreach($custom as $key => $value){
            $order_id = $value->id;
        }
        $content= "http://localhost/qua-tang/index.php?r=home/checkidorder&id=$order_id&activationKey=$tockenkey";
        Util::sendEmailGmail("$custom_email",'Kích Nổ demoVN',$content);
        Yii::app()->user->setFlash('contact','Thank you username da được đăng ký vui lòng vào mail kích hoạt');// tạo flashmesseg
        //$this->redirect('index.php?r=admin/listuser');

        if(isset($_SESSION['cart'])){
            foreach($_SESSION['cart'] as $key =>$value){
                if(is_array($value)){
                    $product_id = $_SESSION['cart'][$key]['id'];//c1
                    $product_name = $value['name'];                  //c2
                    $images =$value['images'];
                    $cost =$value['cost'];
                    $qty = $value['qty'];
                    $sumcost = $value['sumcost'];
                    $order_id;
                    $orderdetail= new orderdetail();
                    $orderdetail->order_id = $order_id;
                    $orderdetail->product_id = $product_id;
                    $orderdetail->product_name = $product_name;
                    $orderdetail->image = $images;
                    $orderdetail->qty = $qty;
                    $orderdetail->cost = $cost;
                    $orderdetail->sumcost = $sumcost;
                    $check2 =$orderdetail->save();
                }

            }
        }
        if(isset($check1)&& $check1!=null &&($check2!=null)){
            session_destroy();
            $this->redirect('index.php?r=home/index');
        }
    }
    public function actionCheckIdOrder(){
        $id = $_GET['id'];
        $activationKey = $_GET['activationKey'];
        $model = new Order();
        $order = $model->findByPk($id);
        if($order -> tockenkey == $activationKey){
            $order->Authentication = 1;
            $order->update();
        }
    }



}